﻿using AutoMapper;
using MediatR;
using MES.Process.API.Application.Command.工艺命令;
using MES.Process.Domain;
using MES.Process.ErrorCode;
using MES.Process.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace MES.Process.API.Application.CommandHandler.工艺命令处理
{
    /// <summary>
    /// 工艺编辑命令处理器
    /// </summary>
    public class CraftsEditCommandHandler : IRequestHandler<CraftsEditCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Crafts> craftsRepository;
        private readonly IBaseRepository<Craft_Process> crRepository;
        private readonly ILogger<CraftsEditCommandHandler> logger;
        private readonly IMapper mapper;
        public CraftsEditCommandHandler(IBaseRepository<Crafts> craftsRepository, ILogger<CraftsEditCommandHandler> logger = null, IMapper mapper = null, IBaseRepository<Craft_Process> crRepository = null)
        {
            this.craftsRepository = craftsRepository;
            this.logger = logger;
            this.mapper = mapper;
            this.crRepository = crRepository;
        }

        public async Task<APIResult<int>> Handle(CraftsEditCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var res=mapper.Map<Crafts>(request);
                if (request.IsUpdOrDel == false)
                {
                    #region 工序修改
                    var exists = await craftsRepository.GetValues()
                        .AnyAsync(x => x.CraftsCode == request.CraftsCode && x.ID != request.ID, cancellationToken);
                    if (exists)
                    {
                        result.Code = APIEnums.Fail;
                        result.Message = "工艺编号已存在";
                        return result;
                    }
                    //获取拥有工序数量
                    if (!string.IsNullOrEmpty(request.Pidlist))
                    {
                        res.HaveProcess = request.Pidlist.Split(',').Select(x => int.Parse(x)).Count();
                    }
                    else
                    {
                        res.HaveProcess = 0;
                    }
                    var list = crRepository.GetValues().Where(x => x.CraftsId == request.ID);
                    int index = 0;
                    using (var ts = await craftsRepository._context.Database.BeginTransactionAsync(cancellationToken)) 
                    {

                        try
                        {
                            //先删除拥有的工序
                            await crRepository.DeleteRangeAsync(list.ToList());

                            //判断是否有新工序添加
                            if (!string.IsNullOrEmpty(request.Pidlist))
                            {
                                List<Craft_Process> craft_Processes = request.Pidlist
                                .Split(',')
                                .Select(pidStr =>
                                {
                                    index++;
                                    return new Craft_Process
                                    {
                                        CraftsId = request.ID,
                                        ProcessId = int.Parse(pidStr),
                                        StepId = index
                                    };
                                }).ToList();
                                await crRepository.AddRangeAsync(craft_Processes);
                            }
                            result.Code = APIEnums.Success;
                            result.Message = "修改成功";
                            result.Data = await craftsRepository.UpdateAsync(res);
                            await ts.CommitAsync(cancellationToken);
                        }
                        catch (Exception ex)
                        {

                            await ts.RollbackAsync(cancellationToken);
                        }
                    }
                    return result;
                    #endregion 
                }
                #region 删除工艺（涵盖工序）
                else
                {
                    using (var ts = await craftsRepository._context.Database.BeginTransactionAsync(cancellationToken)) 
                    {
                        try
                        {
                            //如果该工艺下存在工序先清除工序
                            if (request.HaveProcess > 0)
                            {
                                var plist = crRepository.GetValues().Where(x => x.CraftsId == request.ID);
                                await crRepository.DeleteRangeAsync(plist.ToList());

                            }
                            res.IsDelete = true;
                            result.Code = APIEnums.Success;
                            result.Message = "工艺删除成功";
                            result.Data = await craftsRepository.UpdateAsync(res);
                            await ts.CommitAsync(cancellationToken);

                        }
                        catch (Exception ex)
                        {

                            await ts.RollbackAsync(cancellationToken);
                        }
                    }
                    return result;
                    ;
                   
                }
                #endregion

            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
